package cn.myjerry.test.Rhino;

import java.util.List;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

/**
 * 测试脚本引擎执行javascript代码
 * @author Jerry
 *
 */
public class Demo01 {
	public static void main(String[] args) throws Exception {
		// 获得脚本引擎对象
		ScriptEngineManager sem = new ScriptEngineManager();
		ScriptEngine engine = sem.getEngineByName("javascript");
		
		// 定义变量，存储到引擎上下文中
		engine.put("msg", "恭喜你");
		String str = "var user = {name: 'Jerry', age: 18};";
		str += "print(user.name);";
		
		engine.eval(str);
		engine.eval("msg='Jerry is a good man';");
		System.out.println(engine.get("msg"));
		
		System.out.println("++++++++++++++++++++++++++++++++++");
		
		// 定义函数
		engine.eval("function add(a,b){var num=a+b;return num;};");
		// 执行js函数
		Invocable invocable = (Invocable) engine;
		Object result1 = invocable.invokeFunction("add", new Object[]{13, 23});
		System.out.println(result1);
		
		// 导入其他java包，使用其他包的java类
		String jsCode = "var list = java.util.Arrays.asList([\"警校\",\"军校\"])";
		engine.eval(jsCode);
		
		List<String> list2 = (List<String>) engine.get("list");
		
		for(String temp:list2) {
			System.out.println(temp);
		}
		
	}
}
